/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import com.android.settings.ChooseLockSettingsHelper;
import com.android.settings.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.security.KeyStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import android.content.SharedPreferences;
import android.content.Context;
import android.text.TextUtils;

import com.hisense.settings.channel.AutoScanActivity;
import com.hisense.settings.channel.ChannelSettings;
//import com.marvell.willowtv.framework.features.ParentalControl;
//import com.marvell.willowtv.framework.features.TvFramework;


public class ParentalLockPassword extends Activity implements TextWatcher,
        DialogInterface.OnClickListener, DialogInterface.OnDismissListener {

	public static final String LOG_TAG = "ParentalLockPassword";
    public static final String PREFS_NAME = "ParentalLockPasswordPrefs";
    public static final String KEY_LOCK_PASSWORD = "ParentalLockPassword";
	
    public static final String ACTION_SET_PASSWORD = "com.android.parentallock.SET_PASSWORD";
    public static final String ACTION_CHANGE_PASSWORD = "com.android.parentallock.ACTION_CHANGE_PASSWORD";
    public static final String ACTION_VERIFY_PASSWORD = "com.android.parentallock.ACTION_VERIFY_PASSWORD";
	

    private TextView mOldPassword;
    private TextView mNewPassword;
    private TextView mConfirmPassword;
    private TextView mError;
    private Button mButton;


	String mOldPasswordValue = "0000";
	String mRootPasswordValue="0532";
    private boolean mSubmit = false;

    private String activityIntent=null;
    private int tunerMode;

    // USDTVFramework instance
    //private final TvFramework mFrameInst = TvFramework.getInstance();
    
    // ParentalControlSettings instance

    //private final ParentalControl mPCSettings = mFrameInst.getParentalControlInstance();

    private Intent intent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        intent = getIntent();
        if (getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                activityIntent = bundle.getString("ActivityIntent");
                MyLog.d(PREFS_NAME, "activityIntent:"+activityIntent);
                tunerMode = bundle.getInt("TunerMode");
                MyLog.d(PREFS_NAME, "tunerMode:"+tunerMode);
                }
            }
        String action = intent.getAction();
		
        //SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_WORLD_READABLE);
        //mOldPasswordValue = settings.getString(KEY_LOCK_PASSWORD, "0000");
		//int pass = mPCSettings.getParentalPin();
        int pass = 0;
		mOldPasswordValue = String.format("%04d", pass);
        if (ACTION_CHANGE_PASSWORD.equals(action)) {

            showPasswordDialog(false);
        }else if (ACTION_SET_PASSWORD.equals(action)) {

            showPasswordDialog(TextUtils.isEmpty(mOldPasswordValue));
		}else if (ACTION_VERIFY_PASSWORD.equals(action)) {

			showUnlockDialog();
        } else {
	        if (TextUtils.isEmpty(mOldPasswordValue))
	           showPasswordDialog(true);
			
			else
				showUnlockDialog();
			
        }
    }

    private void savePassword(String newPassword) {
        if (!TextUtils.isEmpty(newPassword)) {
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_WORLD_READABLE);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(KEY_LOCK_PASSWORD, newPassword);
			// Commit the edits!
			editor.commit();
			//mPCSettings.setParentalPin(Integer.parseInt(newPassword));
            setResult(RESULT_OK);
        }
    }
    private void showUnlockDialog() {
        View view = View.inflate(this, R.layout.parentallock_dialog, null);

        ((TextView) view.findViewById(R.id.hint)).setText(R.string.parentallock_unlock_hint);
        mOldPassword = (TextView) view.findViewById(R.id.old_password);
        mOldPassword.setVisibility(View.VISIBLE);
        mOldPassword.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_DONE);
        mOldPassword.addTextChangedListener(this);
        mError = (TextView) view.findViewById(R.id.error);
 
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .setTitle(R.string.parentallock_unlock)
                .setPositiveButton(android.R.string.ok, this)
                .setNegativeButton(android.R.string.cancel, this)
                .create();
        dialog.setOnDismissListener(this);
        dialog.show();
        mButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        mOldPassword.setNextFocusForwardId(DialogInterface.BUTTON_POSITIVE);
        mButton.setEnabled(false);

    }
	
    private void showPasswordDialog(boolean firstTime) {
        View view = View.inflate(this, R.layout.parentallock_dialog, null);

        ((TextView) view.findViewById(R.id.hint)).setText(R.string.parentallock_password_hint);
        if (!firstTime) {
            view.findViewById(R.id.old_password_prompt).setVisibility(View.VISIBLE);
            mOldPassword = (TextView) view.findViewById(R.id.old_password);
            mOldPassword.setVisibility(View.VISIBLE);
            mOldPassword.addTextChangedListener(this);
        }
        view.findViewById(R.id.new_passwords).setVisibility(View.VISIBLE);
        mNewPassword = (TextView) view.findViewById(R.id.new_password);
        mNewPassword.addTextChangedListener(this);
        mConfirmPassword = (TextView) view.findViewById(R.id.confirm_password);
        mConfirmPassword.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE);
        mConfirmPassword.addTextChangedListener(this);
        mError = (TextView) view.findViewById(R.id.error);

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .setTitle(R.string.parentallock_set_password)
                .setPositiveButton(android.R.string.ok, this)
                .setNegativeButton(android.R.string.cancel, this)
                .create();
        dialog.setOnDismissListener(this);
        dialog.show();

        mConfirmPassword.setNextFocusForwardId(DialogInterface.BUTTON_POSITIVE);
        mButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        mButton.setEnabled(false);
    }

    public void afterTextChanged(Editable editable) {
        if ((mOldPassword == null || mOldPassword.getText().length() > 0) &&
            (mNewPassword == null || mNewPassword.getText().length() >= 4) &&
            (mConfirmPassword == null || mConfirmPassword.getText().length() >= 4)) {
            mButton.setEnabled(true);
        } else {
            mButton.setEnabled(false);
        }
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    public void onTextChanged(CharSequence s,int start, int before, int count) {
    }

    public void onClick(DialogInterface dialog, int button) {
        mSubmit = (button == DialogInterface.BUTTON_POSITIVE);
    }
	public void onDismiss(DialogInterface dialog) {
		MyLog.d(LOG_TAG, "onDismiss-mSubmit"+mSubmit);
        if (mSubmit) {
            mSubmit = false;
            mError.setVisibility(View.VISIBLE);
            MyLog.d(LOG_TAG, "onDismiss-mNewPassword"+mNewPassword);
            if (mNewPassword == null) {
				
				String rootValue= mOldPassword.getText().toString();
				MyLog.d(LOG_TAG, "---parental control---rootvalue="+rootValue+",mOldPasswordValue"+mOldPasswordValue);	
				boolean rootflag=rootValue.equals(mRootPasswordValue);
				MyLog.d(LOG_TAG, "--pc password---rootflag="+rootflag);	
			
				if((mOldPassword != null && mOldPassword.getText().toString().equals(mOldPasswordValue))||rootflag){
					final Intent orgIntent = getIntent();
					if (ACTION_VERIFY_PASSWORD.equals(orgIntent.getAction())) {
						if(activityIntent!=null&&activityIntent.contains("Channel")){
		    				Intent resultIntent = new Intent();
		    				resultIntent.putExtra("TunerMode", tunerMode);
		    				MyLog.d(PREFS_NAME, "resultIntent:"+resultIntent);
		    				setResult(Activity.RESULT_OK, resultIntent);
		    				finish();
						}else if(activityIntent!=null&&activityIntent.contains("ResetTV")){
							Intent resultIntent = new Intent();
                            setResult(Activity.RESULT_OK, resultIntent);
                            finish();
						}else{
							Intent intent = new Intent(Intent.ACTION_MAIN);
							intent.setClass(this, ParentalLockSettings.class);
							startActivity(intent);
						}
					}
					setResult(RESULT_OK);
				}
				else
				{
					MyLog.d(LOG_TAG, "--pc password fail");	
					
					mError.setText(R.string.parentallock_wrong_password);
					((AlertDialog) dialog).show();
					return;
				}
            } else {
            	MyLog.d(LOG_TAG, "--pc password new password");	
				
                String newPassword = mNewPassword.getText().toString();
                String confirmPassword = mConfirmPassword.getText().toString();

                if (!newPassword.equals(confirmPassword)) {
                    mError.setText(R.string.parentallock_passwords_mismatch);
                    ((AlertDialog) dialog).show();
                    return;
                } else if (mOldPassword == null) {
					savePassword(newPassword);
                } else if(mOldPassword.getText().toString().equals(mOldPasswordValue)){

					savePassword(newPassword);
                }
				else
				{
                    mError.setText(R.string.parentallock_wrong_password);
					((AlertDialog) dialog).show();
					return;
				}
					
            }

        }
        finish();
    }
}
